package com.iotechn.unimall.admin.myapi.question;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.mapper.mymapper.*;
import com.iotechn.unimall.data.model.Page;
import com.iotechn.unimall.mydata.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class IQuestionServiceImpl implements IQuestionService{

    @Autowired
    private IQuestionMapper iQuestionMapper;

    @Autowired
    private IAnswerMapper iAnswerMapper;

    @Autowired
    private IReplyMapper iReplyMapper;

    @Autowired
    private ICategoryMapper iCategoryMapper;

    @Autowired
    private IFollowMapper iFollowMapper;

    @Autowired
    private IScoreMapper iScoreMapper;

    @Autowired
    private IScoreRecordMapper iScoreRecordMapper;

    @Autowired
    private IUserMapper iUserMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(Integer uid, String title, String context, Integer rewardpoints, String category,String category2) throws ServiceException {
        if (uid == null || category.isEmpty()){
            throw new AdminServiceException(ExceptionDefinition.PARAM_NO_EXIST);
        }
        QuestionBean questionBean = new QuestionBean();
        questionBean.setUid(uid);
        questionBean.setTitle(title);
        questionBean.setContext(context);
        questionBean.setRewardpoints(rewardpoints);
        iQuestionMapper.insert(questionBean);
        Integer integer = iQuestionMapper.selectMaxId();

        CategoryBean categoryBean = new CategoryBean();
        categoryBean.setQuestionid(integer);
        categoryBean.setCategory(category);

        CategoryBean categoryBean1 = new CategoryBean();
        categoryBean1.setQuestionid(integer);
        categoryBean1.setCategory(category2);

        iCategoryMapper.insert(categoryBean);
        iCategoryMapper.insert(categoryBean1);

        return true;
    }

    @Override
    public List<QuestionBean> ownQuestionlist(Integer userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",userId);
        List<QuestionBean> questionBeans = iQuestionMapper.selectByMap(map);
        return questionBeans;
    }

    @Override
    public Page<QuestionBean> list(Integer pageNo, Integer limit,String category) throws ServiceException {
        return iQuestionMapper.getQuestionList(Page.div(pageNo, limit, QuestionBean.class), category);
    }

    @Override
    public List<QuestionBean> listAll(Integer pageNo, Integer limit) throws ServiceException {

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<QuestionBean> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNo, limit);

        List<QuestionBean> records = iQuestionMapper.selectPage(page, new QueryWrapper<>()).getRecords();
        for (QuestionBean record : records) {
            User user = iUserMapper.selectById(record.getUid());
            record.setNickName(user.getNickname());
            record.setName(user.getName());
            record.setCategory(getCategory(Integer.parseInt(record.getId().toString())));
        }
        return records;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setBestAnswer(Integer questionId, Integer answerId) {
        iQuestionMapper.setBestAnswer(questionId,answerId);
        iAnswerMapper.setBestAnswer(answerId);

        AnswerBean answerBean = iAnswerMapper.selectById(answerId);
        Integer uid = answerBean.getUid();

        //加积分
        ScoreBean scoreBean = iScoreMapper.selectOne(new QueryWrapper<ScoreBean>().eq("uid", uid));
        if(scoreBean!=null&&scoreBean.getUid()!=null){
            Integer score = scoreBean.getScore();
            score+=5;
            scoreBean.setScore(score);
            iScoreMapper.updateById(scoreBean);
        }else{
            ScoreBean score = new ScoreBean();
            score.setUid(Long.parseLong(uid.toString()));
            score.setScore(5);
            iScoreMapper.insert(score);
        }

        //记录积分来源
        ScoreRecordBean recordBean = new ScoreRecordBean();
        recordBean.setUid(Long.parseLong(uid.toString()));
        recordBean.setMethod("最佳回答加5分");
        recordBean.setScore(5);
        iScoreRecordMapper.insert(recordBean);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setLoveNumber(Integer questionId, Integer userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",userId);
        map.put("questionId",questionId);
        List<FollowBean> beans = iFollowMapper.selectByMap(map);

        QuestionBean questionBean = iQuestionMapper.selectById(questionId);
        Integer lovenumber = questionBean.getLovenumber();
        if(lovenumber==null)
            lovenumber=0;

        //如果不存在 则增加红心
        if (beans.isEmpty()){

            lovenumber++;
            questionBean.setLovenumber(lovenumber);
            iQuestionMapper.updateById(questionBean);

            FollowBean followBean = new FollowBean();
            followBean.setUid(userId);
            followBean.setQuestionid(questionId);
            iFollowMapper.insert(followBean);
        }else{
            //如果存在 则删除这个关注并且减少一个红心

            lovenumber--;
            questionBean.setLovenumber(lovenumber);
            iQuestionMapper.updateById(questionBean);
            iFollowMapper.deleteByMap(map);

        }
        return true;
    }

    @Override
    public List<QuestionBean> followQuestionList(Integer userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",userId);
        List<FollowBean> followBeans = iFollowMapper.selectByMap(map);
        List<Integer> ids=new ArrayList<>();
        for (FollowBean follow:followBeans
             ) {
            ids.add(follow.getQuestionid());
        }
        List<QuestionBean> questionBeans = iQuestionMapper.selectBatchIds(ids);

        return questionBeans;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createAnswer(Integer uid, Integer questionid, String context) {
        AnswerBean answerBean = new AnswerBean();
        answerBean.setUid(uid);
        answerBean.setQuestionid(questionid);
        answerBean.setContext(context);
        iAnswerMapper.insert(answerBean);
        Integer uid2 = answerBean.getUid();

        //加积分
        ScoreBean scoreBean = iScoreMapper.selectOne(new QueryWrapper<ScoreBean>().eq("uid", uid2));
        if(scoreBean!=null&&scoreBean.getUid()!=null){
            Integer score = scoreBean.getScore();
            score+=1;
            scoreBean.setScore(score);
            iScoreMapper.updateById(scoreBean);
        }else{
            ScoreBean score = new ScoreBean();
            score.setUid(Long.parseLong(uid2.toString()));
            score.setScore(1);
            iScoreMapper.insert(score);
        }

        //记录积分来源
        ScoreRecordBean recordBean = new ScoreRecordBean();
        recordBean.setUid(Long.parseLong(uid2.toString()));
        recordBean.setMethod("回答问题加1分");
        recordBean.setScore(1);
        iScoreRecordMapper.insert(recordBean);

        return true;
    }

    @Override
    public List<AnswerBean> answerList(Integer questionId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("questionId",questionId);
        List<AnswerBean> answerBeans = iAnswerMapper.selectByMap(map);
        for (AnswerBean answerBean : answerBeans) {
            User user = iUserMapper.selectById(answerBean.getUid());
            answerBean.setNickName(user.getNickname());
        }
        return answerBeans;
    }

    @Override
    public List<AnswerBean> myAnswerList(Integer userId) throws ServiceException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",userId);
        List<AnswerBean> answerBeans = iAnswerMapper.selectByMap(map);
        return answerBeans;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setLikes(Integer answerId) {
        AnswerBean answerBean = iAnswerMapper.selectById(answerId);
        Integer likes = answerBean.getLikes();
        if(likes==null){
            likes=0;
        }
        likes++;
        answerBean.setLikes(likes);
        iAnswerMapper.updateById(answerBean);
        return true;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createReply(Integer uid, Integer answerid, String context) {
        ReplyBean replyBean = new ReplyBean();
        replyBean.setAnswerid(answerid);
        replyBean.setContext(context);
        replyBean.setUid(uid);
        iReplyMapper.insert(replyBean);
        return true;
    }

    @Override
    public List<String> getCategory(Integer questionId) throws ServiceException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("questionId",questionId);

        ArrayList<String> objects = new ArrayList<>();
        List<CategoryBean> categoryBeans = iCategoryMapper.selectByMap(map);
        for (CategoryBean categoryBean : categoryBeans) {
            objects.add(categoryBean.getCategory());
        }
        return objects;
    }

    @Override
    public QuestionBean getQuestion(Integer questionId) throws ServiceException {

        return iQuestionMapper.selectById(questionId);
    }

    @Override
    public List<ReplyBean> getReply(Integer answerid) throws ServiceException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("answerId",answerid);

        List<ReplyBean> replyBeans = iReplyMapper.selectByMap(map);
        for (ReplyBean replyBean : replyBeans) {
            User user = iUserMapper.selectById(replyBean.getUid());
            replyBean.setNickName(user.getNickname());
        }
        return  replyBeans;
    }
}
